<template>
  <el-form
    :model="formData"
    ref="formRef"
    @submit.prevent
    :rules="formRules"
    label-width="80px"
    :disabled="mode === 'look' || mode === 'approve'"
  >
    <el-form-item label="承接单位" prop="deptCode">
      <el-select
        v-model="formData.deptCode"
        placeholder="请选择承接单位"
        class="custom-select-width"
        @change="changeDept"
      >
        <el-option
          v-for="item in deptList"
          :key="item.label"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="资金来源" prop="fundsSource">
      <el-select
        v-model="formData.fundsSource"
        filterable
        class="custom-select-width"
      >
        <el-option
          v-for="item in FUNDS_SOURCE"
          :key="item.dicCode"
          :label="item.dicValue"
          :value="item.dicCode"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="经费类别" prop="feeTypeName">
      <el-input v-model="formData.feeTypeName" readonly>
        <template #append>
          <el-button icon="el-icon-search" @click="handleFundType" />
        </template>
      </el-input>
    </el-form-item>

    <el-form-item label="经费金额" prop="spendAmount">
      <el-input
        :disabled="isApproval"
        type="number"
        v-model="formData.spendAmount"
        placeholder="请输入金额"
      >
        <template #append>元</template>
      </el-input>
    </el-form-item>
  </el-form>

  <el-row justify="end" v-if="mode !== 'look' && mode !== 'approve'">
    <el-button @click="handleSubmit(false)">取 消</el-button>
    <el-button type="primary" @click="handleSubmit(true)">提 交</el-button>
  </el-row>
  <el-row justify="end" v-if="mode === 'approve'">
    <el-button type="primary" @click="reject()">驳回</el-button>
    <el-button type="primary" @click="approve()">通过</el-button>
  </el-row>

  <FundsTypeDialogVue
    :isshow="isshow"
    v-if="isshow"
    @emitFundsCheck="emitFundsCheck"
  />
</template>

<script lang="ts">
import { reactive, defineComponent, toRefs, ref, toRef, onMounted } from "vue";
import { cloneDeep } from "lodash-es";
// @ts-ignore
import {
  addFeeSpend,
  approveFeeSpend,
  rejectFeeSpend,
  updateFeeSpend
} from "/@/api/funds";
// @ts-ignore
import NotifMessage from "/@/utils/message/notification";
import { FUNDS_SOURCE, FUNDING_CATEGORY } from "../types";
import { useRoute } from "vue-router";
import { getProjectInfo } from "/@/api/project";
import FundsTypeDialogVue from "./fundsTypeDialog.vue";

export default defineComponent({
  emits: ["emitSubmit"],
  components: { FundsTypeDialogVue },
  props: {
    mode: {
      type: String,
      require: true,
      default: "add"
    },
    companyInfo: {
      type: Object,
      default: () => {}
    }
  },
  setup(props, { emit }) {
    const route = useRoute();
    const formRef = ref<HTMLFormElement | null>(null) as any;
    const currentInfo = toRef(props, "companyInfo");

    const isshow = ref(false);

    let state = reactive({
      formData: {
        id: null,
        deptCode: null,
        deptName: "",
        fundsSource: "",
        feeTypeName: "",
        spendAmount: 0,
        projectId: +route.query.id
      },
      deptList: []
    });

    const formRules = ref({
      deptCode: [
        { required: true, message: "请选择承接单位", trigger: "change" }
      ],
      fundsSource: [
        { required: true, message: "请选择资金来源", trigger: "change" }
      ],
      feeTypeName: [
        { required: true, message: "请选择经费类别", trigger: "change" }
      ],
      spendAmount: [
        { required: true, message: "请输入经费金额", trigger: "change" }
      ]
    });

    if (props.mode !== "add") {
      const copyCurrentInfo = cloneDeep(currentInfo.value);
      state.formData = copyCurrentInfo;
    }

    const approve = async () => {
      try {
        const { code, message } = await approveFeeSpend(state.formData.id);
        if (code === 200) {
          NotifMessage.success(`${message}`);
          requestSuccess(code, message, true);
        } else {
          NotifMessage.error(`${message}`);
        }
      } catch (err) {
        console.log(err);
      }
    };

    const reject = async () => {
      try {
        const { code, message } = await rejectFeeSpend(state.formData.id);
        if (code === 200) {
          NotifMessage.success(`${message}`);
          requestSuccess(code, message, true);
        } else {
          NotifMessage.error(`${message}`);
        }
      } catch (err) {
        console.log(err);
      }
    };

    const getDeptList = async () => {
      const { data } = await getProjectInfo({ id: route.query.id });
      if (data.projectUnderUnit) {
        const deptList = JSON.parse(data.projectUnderUnit);
        state.deptList = deptList.map(el => {
          return {
            label: el.name,
            value: el.code
          };
        });
      }
    };

    const changeDept = item => {
      state.formData.deptName = state.deptList.find(
        el => el.value === item
      ).label;
    };

    // 确认提交或者取消
    const handleSubmit = async (isSubmit): Promise<void> => {
      if (isSubmit) {
        const isValid = await new Promise(resolve =>
          formRef.value.validate(resolve)
        );
        if (!isValid) return;
        state.formData["approveStatus"] = "2";
        // console.log(state.formData);
        if (props.mode === "edit") {
          const { code, message } = await updateFeeSpend(state.formData);
          requestSuccess(code, message, isSubmit);
        } else {
          const { code, message } = await addFeeSpend(state.formData);
          requestSuccess(code, message, isSubmit);
        }
      } else {
        emit("emitSubmit", isSubmit);
      }
    };

    // 统一处理请求结果方法
    const requestSuccess = (
      code: number,
      message: string,
      isSubmit: boolean
    ) => {
      if (code === 200) {
        NotifMessage.success(message);
        emit("emitSubmit", isSubmit);
      }
    };

    const handleFundType = () => {
      isshow.value = true;
    };

    const emitFundsCheck = val => {
      if (val) {
        state.formData.feeTypeName = val;
      }
      isshow.value = false;
    };

    onMounted(() => {
      getDeptList();
    });

    return {
      ...toRefs(state),
      isshow,
      formRef,
      formRules,
      handleSubmit,
      FUNDS_SOURCE,
      FUNDING_CATEGORY,
      changeDept,
      emitFundsCheck,
      handleFundType,
      approve,
      reject
    };
  }
});
</script>

<style lang="scss" scoped>
.custom-select-width {
  width: 100% !important;
}
</style>
